/**
 *
 */
package com.ybkj.daijia.api.driver.v1;

import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.driver.ErrorConstant;
import com.ybkj.daijia.api.driver.SecurityUtils;
import com.ybkj.daijia.api.driver.transport.ChartDetailTransport;
import com.ybkj.daijia.api.driver.transport.ChartTransport;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.OrderService;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author bo
 *
 */
@Controller
@RequestMapping(value = "driver/api/rest/v1")
public class OrderChartController {

    private static final Logger logger = LoggerFactory.getLogger(OrderChartController.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private SettingUtils settingUtils;

    /**
     * 数据统计
     *
     * @param driverID
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "dataForIndex")
    public @ResponseBody
    ResultTransport dataForIndex(Long driverID, String appKey, String token, String timestamp) {

        logger.debug("recv driverID:{},appKey:{},token:{},timestamp:{}", driverID, appKey, token,
            timestamp);

        if (null == driverID || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp)
            || !SecurityUtils.checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            //执行统计查询
            Setting setting = settingUtils.get();

            //查询今日订单
            Calendar calendaer = Calendar.getInstance();
            calendaer.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.SECOND, 0);
            Date begin = calendaer.getTime();
            Date end = DateUtils.addHours(begin, 24);
            //计算单量与总价
            ChartTransport chartTran = new ChartTransport();
            long todayTasks = orderService.counByDriverAndFinishTime(driverID, begin, end);
            double todayIncome = orderService.sumByDriverAndFinishTime(driverID, begin, end);
            chartTran.setTodayTasks(todayTasks);
            chartTran.setTodayIncome(todayIncome);

            //查询昨日订单
            begin = DateUtils.addHours(begin, -24);
            end = DateUtils.addHours(end, -24);
            long yesterdayTasks = orderService.counByDriverAndFinishTime(driverID, begin, end);
            double yesterdayIncome = orderService.sumByDriverAndFinishTime(driverID, begin, end);

            chartTran.setYesterdayTasks(yesterdayTasks);
            chartTran.setYesterdayIncome(yesterdayIncome);

            //查询本月
            calendaer = Calendar.getInstance();
            calendaer.set(Calendar.DAY_OF_MONTH, calendaer.getActualMinimum(Calendar.DAY_OF_MONTH));
            calendaer.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.MILLISECOND, 0);
            begin = calendaer.getTime();

            calendaer.set(Calendar.DAY_OF_MONTH, calendaer.getActualMaximum(Calendar.DAY_OF_MONTH));
            calendaer.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.MILLISECOND, 0);
            end = calendaer.getTime();
            end = DateUtils.addDays(end, 24);

            long thisMonthTasks = orderService.counByDriverAndFinishTime(driverID, begin, end);
            double thisMonthIncome = orderService.sumByDriverAndFinishTime(driverID, begin, end);

            chartTran.setThisMonthTasks(thisMonthTasks);
            chartTran.setThisMonthIncome(thisMonthIncome);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(chartTran);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver modifyPass error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 获取今日订单
     * @param driverID
     * @param page
     * @param limit
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "dataForToday")
    public @ResponseBody
    ResultTransport dataForToday(Long driverID, Integer page, Integer limit, String appKey,
        String token, String timestamp) {

        logger.debug("recv driverID:{},page:{},limit:{},appKey:{},token:{},timestamp:{}", driverID,
            page, limit, appKey, token, timestamp);

        if (null == driverID || null == page || null == limit || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp)
            || !SecurityUtils.checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            //执行统计查询
            Setting setting = settingUtils.get();

            Calendar nowCalendar = Calendar.getInstance();
            int nowHour = nowCalendar.get(Calendar.HOUR_OF_DAY);

            //查询今日订单
            Calendar calendaer = Calendar.getInstance();
            calendaer.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.SECOND, 0);
            Date end = calendaer.getTime();
            Date begin = DateUtils.addHours(end, -24);
            if (setting.getWorkBegin() < nowHour) {
                end = DateUtils.addHours(end, 24);
                begin = DateUtils.addHours(begin, 24);
            }

            long totalTask = orderService.counByDriverAndFinishTime(driverID, begin, end);
            double totalIncome = orderService.sumByDriverAndFinishTime(driverID, begin, end);

            Page<Order> pageOrders = orderService
                .findByDriverAndFinishTime(driverID, begin, end, page, limit);
            //计算单量与总价
            ChartDetailTransport chartTran = new ChartDetailTransport();

            chartTran.setTotalTasks(totalTask);
            chartTran.setTotalIncome(totalIncome);
            chartTran.setOrders(pageOrders.getContent());
            chartTran.setTotalPage(pageOrders.getTotalPages());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(chartTran);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver modifyPass error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 统计昨天的订单数据
     * @param driverID
     * @param page
     * @param limit
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "dataForYesterday")
    public @ResponseBody
    ResultTransport dataForYesterday(Long driverID, Integer page, Integer limit, String appKey,
        String token, String timestamp) {

        logger.debug("recv driverID:{},page:{},limit:{},appKey:{},token:{},timestamp:{}", driverID,
            page, limit, appKey, token, timestamp);

        if (null == driverID || null == page || null == limit || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp)
            || !SecurityUtils.checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            //执行统计查询
            Setting setting = settingUtils.get();

            Calendar nowCalendar = Calendar.getInstance();
            int nowHour = nowCalendar.get(Calendar.HOUR_OF_DAY);

            Calendar calendaer = Calendar.getInstance();
            calendaer.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.SECOND, 0);
            Date end = calendaer.getTime();
            Date begin = DateUtils.addHours(end, -24);
            if (setting.getWorkBegin() < nowHour) {
                end = DateUtils.addHours(end, 24);
                begin = DateUtils.addHours(begin, 24);
            }
            begin = DateUtils.addHours(begin, -24);
            end = DateUtils.addHours(end, -24);

            long totalTask = orderService.counByDriverAndFinishTime(driverID, begin, end);
            double totalIncome = orderService.sumByDriverAndFinishTime(driverID, begin, end);

            Page<Order> pageOrders = orderService
                .findByDriverAndFinishTime(driverID, begin, end, page, limit);
            //计算单量与总价
            ChartDetailTransport chartTran = new ChartDetailTransport();

            chartTran.setTotalTasks(totalTask);
            chartTran.setTotalIncome(totalIncome);
            chartTran.setOrders(pageOrders.getContent());
            chartTran.setTotalPage(pageOrders.getTotalPages());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(chartTran);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver modifyPass error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "dataForThisMonth")
    public @ResponseBody
    ResultTransport dataForThisMonth(Long driverID, Integer page, Integer limit, String appKey,
        String token, String timestamp) {

        logger.debug("recv driverID:{},page:{},limit:{},appKey:{},token:{},timestamp:{}", driverID,
            page, limit, appKey, token, timestamp);

        if (null == driverID || null == page || null == limit || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp)
            || !SecurityUtils.checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            //执行统计查询
            Setting setting = settingUtils.get();

            //查询本月订单
            Calendar calendaer = Calendar.getInstance();
            calendaer.set(Calendar.DAY_OF_MONTH, calendaer.getActualMinimum(Calendar.DAY_OF_MONTH));
            calendaer.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.MILLISECOND, 0);
            Date begin = calendaer.getTime();

            calendaer.set(Calendar.DAY_OF_MONTH, calendaer.getActualMaximum(Calendar.DAY_OF_MONTH));
            calendaer.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.MILLISECOND, 0);
            Date end = calendaer.getTime();
            end = DateUtils.addDays(end, 24);

            long totalTask = orderService.counByDriverAndFinishTime(driverID, begin, end);
            double totalIncome = orderService.sumByDriverAndFinishTime(driverID, begin, end);

            Page<Order> pageOrders = orderService
                .findByDriverAndFinishTime(driverID, begin, end, page, limit);
            //计算单量与总价
            ChartDetailTransport chartTran = new ChartDetailTransport();

            chartTran.setTotalTasks(totalTask);
            chartTran.setTotalIncome(totalIncome);
            chartTran.setOrders(pageOrders.getContent());
            chartTran.setTotalPage(pageOrders.getTotalPages());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(chartTran);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver modifyPass error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "dataForAll")
    public @ResponseBody
    ResultTransport dataForAll(Long driverID, Integer page, Integer limit, String appKey,
        String token, String timestamp) {

        logger.debug("recv driverID:{},page:{},limit:{},appKey:{},token:{},timestamp:{}", driverID,
            page, limit, appKey, token, timestamp);

        if (null == driverID || null == page || null == limit || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp)
            || !SecurityUtils.checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            long totalTask = orderService.counByDriver(driverID);
            double totalIncome = orderService.sumByDriver(driverID);

            Page<Order> pageOrders = orderService.findByDriver(driverID, page, limit);
            //计算单量与总价
            ChartDetailTransport chartTran = new ChartDetailTransport();

            chartTran.setTotalTasks(totalTask);
            chartTran.setTotalIncome(totalIncome);
            chartTran.setOrders(pageOrders.getContent());
            chartTran.setTotalPage(pageOrders.getTotalPages());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(chartTran);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver modifyPass error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }
}
